package com.jds.test.websocket;

import com.jds.test.http.HttpServerHandler;
import com.jds.test.http.HttpServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by sunyuming on 18/8/29.
 */
public class WebSocketServerJob implements Runnable {

    static final EventLoopGroup CLIENT_BOSS_LOOP_GROUP = new NioEventLoopGroup(4);
    static final EventLoopGroup CLIENT_WORKER_LOOP_GROUP = new NioEventLoopGroup(4);

    public static void main(String[] args) throws Exception {
        new Thread(new WebSocketServerJob()).start();
    }

    @Override
    public void run() {
        startHttpServer(8990);
    }


    public static void startHttpServer(int port) {
        try {
            ServerBootstrap bs = new ServerBootstrap();
            bs.group(CLIENT_BOSS_LOOP_GROUP, CLIENT_WORKER_LOOP_GROUP);
            bs.channel(NioServerSocketChannel.class);
            bs.childHandler(new WebSocketServerInitializer());
            ChannelFuture future = bs.bind(port).sync();
            System.out.println("web socket server start at " + port);
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CLIENT_BOSS_LOOP_GROUP.shutdownGracefully();
            CLIENT_WORKER_LOOP_GROUP.shutdownGracefully();
        }
    }
}
